<?php

namespace app\admin\controller\Subject;

use app\common\controller\Backend;

use think\exception\PDOException;
use Exception;

class Subject extends Backend
{
    // 当前对象模型
    protected $model = null;

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'id,title,category.id';

    /**
     * 是否是关联查询
     */
    protected $relationSearch = true;

    public function __construct()
    {
        parent::__construct();

        $this->model = model('Subject.Subject');
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }

        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        $list = $this->model
            ->with('category')
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    // 新增课程
    public function add()
    {
        $CateData = model('Subject.Category')->order('weight DESC')->column('id,name');

        if ($this->request->isPost()) {
            $params = $this->request->param('row/a');

            if (empty($params)) {
                $this->error('参数项不能为空');
            }



            $result = $this->model->validate('common/Subject/Subject')->save($params);



            if ($result === FALSE) {
                if (!empty($params['thumbs'])) {
                    $thumbsArr = explode(',', $params['thumbs']);

                    $thumbsArr = array_filter($thumbsArr);

                    foreach ($thumbsArr as $thumb) {
                        @is_file('.' . $thumb) && @unlink('.' . $thumb);
                    }
                }
                $this->error($this->model->getError());
            } else {
                $this->success();
            }
        }

        $this->assign([
            'CateData' => $CateData
        ]);

        return $this->fetch();
    }

    public function edit($ids = 0)
    {
        $subject = $this->model->find($ids);

        if (!$subject) {
            $this->error('该课程不存在');
        }

        if ($this->request->isPost()) {
            $params = $this->request->param('row/a');

            if (empty($params)) {
                $this->error('参数项不能为空');
            }

            // 追加id
            $params['id'] = $ids;


            $result = $this->model->isUpdate(true)->save($params);

            if ($result === FALSE) {
                if (!empty($params['thumbs']) && $subject['thumbs'] != $params['thumbs']) {
                    // 获取旧的图片
                    $thumbsArr = explode(',', $subject['thumbs']);

                    $thumbsArr = array_filter($thumbsArr);

                    // 从表单过来的图片
                    $ThumbsArr = explode(',', $params['thumbs']);

                    foreach($ThumbsArr as $val)
                    {
                        if(!in_array($val,$thumbsArr))
                        {
                            @is_file('.' . $val) && unlink('.' . $val);
                        }
                    }
                }

                $this->error();
            } else {
                if (!empty($params['thumbs']) && $subject['thumbs'] != $params['thumbs']) {
                    // 获取旧的图片
                    $thumbsArr = explode(',', $subject['thumbs']);

                    $thumbsArr = array_filter($thumbsArr);

                    // 从表单过来的图片
                    $ThumbsArr = explode(',', $params['thumbs']);

                    foreach ($thumbsArr as $val) {
                        if (!in_array($val, $ThumbsArr)) {
                            @is_file('.' . $val) && unlink('.' . $val);
                        }
                    }
                }

                $this->success();
            }
        }

        // 查询分类的数据
        $CateData = model('Subject.Category')->order('weight DESC')->column('id,name');

        // 赋值
        $this->assign([
            'CateData' => $CateData,
            'subject' => $subject
        ]);

        return $this->fetch();
    }

    // 软删除 => 不是在数据库把数据真实删除
    public function del($ids = null)
    {
        // SELECT * FROM `pre_subject` WHERE `id` IN (9,8)
        $row = $this->model->whereIn('id',$ids)->select();

        if(!$row)
        {
            $this->error('请选择需要删除的数据');
        }

        $count = 0;

        $this->model->startTrans();

        try {
            foreach ($row as $item) {
                $count += $item->delete();
            }
            $this->model->commit();
        } catch (PDOException|Exception $e) {
            $this->model->rollback();
            $this->error($e->getMessage());
        }

        if($count > 0)
        {
            $this->success();
        }else{
            $this->error();
        }
    }

    // 回收站
    public function recyclebin()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }

        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        $list = $this->model
            ->onlyTrashed()
            ->with('category')
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    // 还原
    public function restore($ids = null)
    {
        $row = $this->model->onlyTrashed()->where(['id' => ['in',$ids]])->select();

        if(!$row)
        {
            $this->error('请选择还原数据');
        }

        $result = $this->model->restore(['id' => ['in',$ids]]);

        if($result === FALSE)
        {
            $this->error();
        }else{
            $this->success();
        }

    }

    // 真实删除
    public function destroy($ids = null)
    {
        $row = $this->model->onlyTrashed()->whereIn('id',$ids)->select();

        if(!$row)
        {
            $this->error('请选择需要删除的数据');
        }

        $result = $this->model->destroy($ids,true);

        if($result === FALSE)
        {
            $this->error('删除失败');
        }else{
            foreach($row as $item)
            {
                if(!empty($item['thumbs']))
                {
                    $thumbsArr = explode(',',$item['thumbs']);

                    $thumbsArr = array_filter($thumbsArr);

                    foreach($thumbsArr as $thumb)
                    {
                        @is_file('.'.$thumb) && @unlink('.' . $thumb);
                    }
                }
            }
            $this->success('删除成功');
        }
    }
}
